import React from 'react';

import { CreateReview, ratingApi } from '@/entities/rating';
import { ModalContext } from '@/shared/context/ModalContext';
import { Modals } from '@/shared/interfaces';
import { Title } from '@/shared/ui';

import cs from './Review.module.scss';

export const Review = ({ ratingId, productId }: { ratingId?: number; productId?: string }) => {
  const [star, setStar] = React.useState(0);

  const { data: rating } = ratingApi.useGetSingleProductRatingQuery(
    { ratingId: String(ratingId), productId: String(productId) },
    { skip: !ratingId || !productId },
  );
  const [addRating] = ratingApi.useAddProductRatingMutation();
  const [editRating] = ratingApi.useEditProductRatingMutation();
  const [textValue, setTextValue] = React.useState('');
  const [changed, setChanged] = React.useState(false);
  const { openModal, setData } = React.useContext(ModalContext);
  const [createReview] = ratingApi.useAddProductRatingMutation();
  React.useEffect(() => {
    setStar(rating?.rate as number);
    setTextValue(rating?.comment as unknown as string);
  }, [rating?.comment, rating?.rate, rating?.id]);
  React.useEffect(() => {
    if (!!ratingId && (star !== rating?.rate || textValue !== (rating?.comment as unknown as string))) {
      setChanged(true);
    } else {
      setChanged(false);
    }
  }, [star, textValue]);

  const handleDeleteRating = () => {
    setData(() => ({ ratingId, productId }));
    openModal(Modals.ConfirmDelete);
  };

  const handleSubmit = async () => {
    if (!!ratingId && rating?.id) {
      await editRating({
        rate: star,
        comment: textValue,
        ratingId: +ratingId,
        id: Number(productId),
      }).unwrap();
    } else {
      await addRating({ rate: star, comment: textValue, id: Number(productId) });
    }
    setChanged(false);
    openModal(Modals.RatingSendModal);
  };
  const isRev = textValue?.length > 0 || star > 0;

  return (
    <div className={cs.block}>
      <Title>{ratingId ? 'Изменить отзыв' : 'Оставить отзыв'}</Title>
      <CreateReview
        changed={changed}
        createReview={createReview}
        handleDeleteRating={handleDeleteRating}
        handleSubmit={handleSubmit}
        isBought
        isRating={!!ratingId}
        setStar={setStar}
        setTextValue={setTextValue}
        star={star}
        textValue={textValue}
        withPrevent={(!!ratingId && changed) || (!ratingId && isRev)}
      />
    </div>
  );
};
